package current;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Non-Blocking能力
 */
public class TryLock {

    static class Friend {
        private final String name;
        private final ReentrantLock lock = new ReentrantLock();

        public Friend(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        /**
         * 鞠躬
         */
        public void bow(Friend bower) {
            try {
                lock.tryLock(1000, TimeUnit.MICROSECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.format("%s: %s 向我鞠躬！%n", this.name, bower.getName());

            lock.unlock();
            bower.release(this);
        }

        /**
         * 回鞠躬
         */
        public void release(Friend bower) {
            try {
                lock.tryLock(1000, TimeUnit.MICROSECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.format("%s: %s 回了我！%n", this.name, bower.getName());
            lock.unlock();
        }
    }



    public static void main(String[] args) {
        final Friend xiaoming = new Friend("小明");
        final Friend xiaohong = new Friend("小红");

        new Thread(() -> xiaoming.bow(xiaohong)).start();
        new Thread(() -> xiaohong.bow(xiaoming)).start();

        //     抢占  尝试获取  前提先释放
        // A.bow -> A -> tryB -> releaseA
        // B.bow -> B -> tryA -> releaseB
    }
}
